package cn.itcast.take_delivery.service.impl;

import java.util.Date;
import java.util.UUID;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.constants.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.take_delivery.dao.OrderRepository;
import cn.itcast.take_delivery.service.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private FixedRepository fixedRepository;
	
	@Autowired
	private OrderRepository orderRepository;
	
	@Autowired
	private AreaRepository areaRepository;
	@Override
	public void saveOrder(Order order) {
		// System.out.println(order);
		order.setOrderNum(UUID.randomUUID().toString()); // 设置订单号
		order.setOrderTime(new Date());// 设置下单时间
		order.setStatus("1"); // 待取件

		// 寄件人 省市区
		Area area = order.getSendArea();
		Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(
				area.getProvince(), area.getCity(), area.getDistrict());
		// 收件人 省市区
		Area recArea = order.getSendArea();
		Area persistRecArea = areaRepository
				.findByProvinceAndCityAndDistrict(recArea.getProvince(),
						recArea.getCity(), recArea.getDistrict());
		order.setSendArea(persistArea);
		order.setRecArea(persistRecArea);
	   String fixedAreaId =	WebClient.create(Constants.CRM_MANAGEMENT_HOST
				+ "/crm_management/services/customerService/customer/findFixedAreaIdByAddress?address="
				+ order.getSendAddress()).accept(MediaType.APPLICATION_JSON).get(String.class);
	   if (fixedAreaId != null) {
		   //通过id查询定区
		   FixedArea fixedArea = fixedRepository.findOne(fixedAreaId);
		   //快递员
		   Courier courier = fixedArea.getCouriers().iterator().next();
		   if (courier != null) {
			System.out.println("分单成功");
			order.setCourier(courier);
			order.setOrderNum(UUID.randomUUID().toString());
			
			orderRepository.save(order);
		   }
	   	}
	   
	}//未完成
	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}
	

}
